package io.sdph.controller;

import io.sdph.products.IProductManager;
import io.sdph.products.exceptions.ProductException;
import io.sdph.products.model.Product;
import io.sdph.userprofile.ISessionManager;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Servlet odpowiedzialny za funkcjonalnosc zmodyfikowania wlasnosci produktu w
 * panelu przedstawiciela handlowego (admin.jsp)
 * 
 * @author MODUL FRONTU (WWW)
 */
@Controller
@RequestMapping("/admin/ModifyProduct")
public class AdminModifyProduct {

	private static final String SELECTED_PRODUCT = "products";
	private static final String PRODUCT_NAME = "name";
	private static final String PRODUCT_PRICE = "price";
	private static final String ANOTHER = "all";

	private static final String OUTPUT_ERROR = "errors";
	private static final String PRODUCT_NAME_EMPTY_ERROR = "adminAddProduct.firstName.error.empty";
	private static final String PRODUCT_PRICE_EMPTY_ERROR = "adminAddProduct.lastName.error.empty";

	private static final String PAGE_VIEW = "admin";

	/** Komponent pomocniczy do zarz�dzania sesj� u�ytkownika. */
	@Autowired
	ISessionManager sessionManager;

	@Autowired
	IProductManager productManager;

	// HttpServletRequest arg0, HttpServletResponse arg1
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView showPage() throws Exception {

		ModelAndView model = new ModelAndView(PAGE_VIEW);
		model.addObject("pageName", "products");
		return model;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView adminModifyProduct(
			@RequestParam(SELECTED_PRODUCT) final String selectedProduct,
			@RequestParam(PRODUCT_NAME) final String name,
			@RequestParam(PRODUCT_PRICE) final Double price) {

		ModelAndView model = new ModelAndView(PAGE_VIEW);

		Map<String, String> errors = new HashMap();

		if (StringUtils.isEmpty(name))
			errors.put(PRODUCT_NAME, PRODUCT_NAME_EMPTY_ERROR);

		if (price == null)
			errors.put(PRODUCT_PRICE, PRODUCT_PRICE_EMPTY_ERROR);

		if (errors.isEmpty()) {

			Product product;
			try {
				product = productManager.getProduct(selectedProduct);

				product.setPrice(price);

				productManager.addProduct(product);
			} catch (ProductException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			model.addObject(OUTPUT_ERROR, errors);
		}

		model.addObject("pageName", "products");
		return model;
	}

}
